package com.harmontronics.hanma.paas.paas.domain.app.service.dialect;

import com.harmontronics.hanma.paas.paas.domain.app.entity.valueobject.ViewDataBaseTypeEnum;
import com.harmontronics.hanma.paas.paas.domain.app.repository.persistence.HmDatasourceEnvRepository;
import com.harmontronics.hanma.paas.paas.domain.app.service.HmPublishedEntityModelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.util.Pair;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Service
public class PostgresDialectService extends AbstractDialectService {

    @Autowired
    private HmDatasourceEnvRepository hmDatasourceEnvRepository;

    @Autowired
    private HmPublishedEntityModelService hmPublishedEntityModelService;

    @Override
    public HmDatasourceEnvRepository getHmDatasourceEnvRepository() {
        return hmDatasourceEnvRepository;
    }

    @Override
    public HmPublishedEntityModelService getHmPublishedEntityModelService() {
        return hmPublishedEntityModelService;
    }

    @Override
    public ViewDataBaseTypeEnum getDataBaseType() {
        return ViewDataBaseTypeEnum.POSTGRES;
    }

    private static final String VIEW_INFO_SQL = "SELECT col_description(a.attrelid,a.attnum) as comment,pg_type.typname as typename,a.attname as name, a.attnotnull as notnull\n" +
            "FROM pg_class as c,pg_attribute as a inner join pg_type on pg_type.oid = a.atttypid\n" +
            "where c.relname = ? and a.attrelid = c.oid and a.attnum>0";

    @Override
    public List<ViewColumn> getViewColumns(Long datasourceId, String viewName) {
        Connection connection =null;
        try {
            Pair<String,Connection> pair = getConnection(datasourceId);
            connection = pair.getSecond();
            PreparedStatement ps = connection.prepareStatement(VIEW_INFO_SQL);
            ps.setString(1, viewName);
            ResultSet rs = ps.executeQuery();
            List<ViewColumn> viewColumns = new ArrayList<>();
            while (rs.next()) {
                String type = rs.getString("typename");
                String name = rs.getString("name");
                viewColumns.add(new ViewColumn(name,type));
            }
            rs.close();
            return viewColumns;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }finally {
            if(connection!=null){
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }

}
